const Base = require('./base.js');
// const BigNumber = require('bignumber.js');
const Alipay = require('alipay-node-sdk');
const path = require('path');

module.exports = class extends Base {
  async wxAction() {
    const WeixinSerivce = this.service('weixin', 'min');
    const result = WeixinSerivce.payNotify(this.post('xml'));
    if (!result) {
      return `<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>`;
    }
    const orderTable = await this.model('order_pay').where({
      order_sn: result.out_trade_no
    }).find();

    if (think.isEmpty(orderTable)) {
      return `<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单不存在]]></return_msg></xml>`;
    }
    if (orderTable.status > 0) {
      return '';
    }

    await this.model('order_pay').where({
      order_sn: result.out_trade_no
    }).update({
      status: 1,
      total: result.total_fee,
      method_txt: 'wx小程序'
    });

    if (orderTable.order_id) {
      if (orderTable.remark === '首付') {
        await this.model('order_list').where({
          id: orderTable.order_id
        }).update({
          status: 10,
          pay_method: 'wx小程序',
          pay_time: ['exp', 'CURRENT_TIMESTAMP()']
        });
      }
      if (orderTable.remark === '尾款') {
        await this.model('order_list').where({
          id: orderTable.order_id
        }).update({
          status: 20,
          pay_method: 'wx小程序',
          pay_time_2: ['exp', 'CURRENT_TIMESTAMP()']
        });
      }
    } else if (orderTable.order_no) {
      await this.model('order_list').where({
        order_no: orderTable.order_no
      }).update({
        status: 10,
        pay_method: 'wx小程序',
        pay_time: ['exp', 'CURRENT_TIMESTAMP()']
      });
    }

    return `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
  }

  async aliAction() {
    const response = this.post();

    var ali = new Alipay({
      appId: '2021003124622464',
      notifyUrl: 'https://apiyumi.keji.cn/api/payNotify/ali',
      rsaPrivate: path.resolve('./cert/private.pem'),
      rsaPublic: path.resolve('./cert/public.pem'),
      signType: 'RSA2'
    });

    const ok = ali.signVerify(response);

    if (ok && response.trade_status === 'TRADE_SUCCESS') {
      const orderTable = await this.model('recharge_list').where({
        order_no: response.out_trade_no
      }).find();

      if (think.isEmpty(orderTable)) {
        return false;
      }

      if (orderTable.type > 0) {
        return '';
      }

      await this.model('order_pay').where({
        order_no: response.out_trade_no
      }).update({
        type: 1,
        total: response.total_amount * 100,
        method_txt: 'ali'
      });

      await this.model('domain_list').where({
        order_no: response.out_trade_no
      }).update({
        fabu_pay: 1,
        fabu_method: 'ali'
      });
    }
  }
};
